package com.example.baidumap_a.Activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.baidumap_a.entity.Ohuang;
import com.example.baidumap_a.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import com.example.baidumap_a.R;
public class RechargeActivity extends AppCompatActivity {
    private CheckBox checkBox;
    private int checkIds[] = {R.id.checkbox_recharge_1, R.id.checkbox_recharge_2, R.id.checkbox_recharge_3
            , R.id.checkbox_recharge_4, R.id.checkbox_recharge_5, R.id.checkbox_recharge_6};
    private TextView text_name, text_balance;
    private EditText editText;
    private int money[] = {10, 50, 100, 200, 400, 1000};
    private Dialog dialogLoading;//加载对话框
    private String name;
    final OkHttpClient client = new OkHttpClient();
    private final static int  JSON_OK=0,JSON_NO=1;
   private User user;
   private static final int CM_ERROR=2,CM_SUCCESS=3,CM_OTHER=4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        Intent intent=getIntent();
        name=intent.getStringExtra("username");
        initView();//初始化
    }

    private void initView() {
        text_name=findViewById(R.id.text_name_recharge);
        text_balance=findViewById(R.id.text_balance_recharge);
        text_name.setText("用户名："+name);

        for (int i = 0; i < checkIds.length; i++) {
            checkBox = findViewById(checkIds[i]);
            checkBox.setOnClickListener(CheckBoxClickListener);
        }
        editText = findViewById(R.id.edit_recharge);

        editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    for (int i = 0; i < checkIds.length; i++) {
                        checkBox = findViewById(checkIds[i]);
                        checkBox.setChecked(false);
                    }
                }
            }
        });
        PostHttpRequest();//获取余额
    }
//查询金额
    private void PostHttpRequest() {
        RequestBody formBody = new FormBody.Builder()
                .add("username", name)
                .build();

        final Request request = new Request.Builder()
                .url("https://d30n971042.imdo.co/user/findUser")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
              myHandler.sendEmptyMessage(JSON_NO);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String json = body.string();
                    Gson gson = new Gson();
                    Type type = new TypeToken<User>() {
                    }.getType();
                    user = gson.fromJson(json, type);
                    body.close();
                }

                myHandler.sendEmptyMessage(JSON_OK);
            }
        });
    }


    @SuppressLint("HandlerLeak")
  private   Handler myHandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
           switch (msg.what){
               case JSON_OK:
                   text_balance.setText("余额：￥"+user.getMoney()+"元");
                   break;
               case JSON_NO:
                   Toast.makeText(RechargeActivity.this,"网络错误",Toast.LENGTH_SHORT).show();
                   break;
               case CM_ERROR:
                   dialogLoading.dismiss();
                   Ohuang.dialogshow(RechargeActivity.this,"充值失败","网络错误,充值失败");
                   break;
               case CM_SUCCESS:
                   dialogLoading.dismiss();
                   Ohuang.dialogshow(RechargeActivity.this, "充值成功", "充值成功", new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                           finish();
                       }
                   });
                   break;
               case CM_OTHER:
                   dialogLoading.dismiss();
                   Ohuang.dialogshow(RechargeActivity.this,"充值失败","出现其他错误");
                   break;

           }
        }
    };

    public void CloseRechargeClick(View view) {
        finish();
    }


    //多选按钮点击事件
    View.OnClickListener CheckBoxClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkBox = findViewById(v.getId());
            if (checkBox.isChecked()) {//如果按钮已经被选中
                //实现单选
                for (int i = 0; i < checkIds.length; i++) {
                    checkBox = findViewById(checkIds[i]);
                    checkBox.setChecked(false);
                }
                checkBox = findViewById(v.getId());
                checkBox.setChecked(true);
                editText.setText("");
                editText.clearFocus();
            }
        }
    };

    //点击支付按钮
    public void RechargeClick(View view) {
        String a = editText.getText().toString();
        int qian = 0;//金额
        if (a.isEmpty()) {
            boolean aa = false;
            for (int i = 0; i < checkIds.length; i++) {
                checkBox = findViewById(checkIds[i]);
                if (checkBox.isChecked()) {
                    aa = true;
                    qian = money[i];
                }
            }
            if (aa) {
                payDialogShow("支付金额", qian);//弹出支付对话框
            } else {
                Ohuang.dialogshow(this, "充值失败", "请选择或输入你要充值的金额");//弹出提示对话框
            }

        } else {
            qian = Integer.valueOf(a);
            if (qian > 0) {
                if (qian < 10000) {
                    payDialogShow("充值金额", qian);//弹出支付对话框
                } else {
                    Ohuang.dialogshow(this, "充值失败", "充值金额不能大于1万元。");//弹出提示对话框
                }
            } else {
                Ohuang.dialogshow(this, "充值失败", "充值金额不能为0元");//弹出提示对话框
            }
        }
    }

    //确认支付对话框
    @SuppressLint("SetTextI18n")
    private void payDialogShow(String a, final int b) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_pay, null);
        final AlertDialog dialog = new AlertDialog.Builder(this, R.style.MyDialog).setView(view).create();
        TextView textView = view.findViewById(R.id.text_title_dialog_pay);
        TextView textView1 = view.findViewById(R.id.text_money_dialog_pay);
        Button button = view.findViewById(R.id.btn_pay_dialog_pay);
        ImageButton imageButton = view.findViewById(R.id.btn_x_dialog_pay);
        textView.setText(a);
        textView1.setText("￥" + b + "元");
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//关闭对话框
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//关闭对话框
                //再执行支付操作
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                            PostHttpRequest(b);
                            PostHttpRequest2(b);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                dialogLoading = Ohuang.dialogLoadingshow(RechargeActivity.this, "正在支付");//显示加载对话框
            }
        });
        dialog.show();//显示
        //需要先显示再设置大小
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.7 * screenWidth);
        window.setAttributes(params);

    }
//充值金额
    private void PostHttpRequest(int money) {
        RequestBody formBody = new FormBody.Builder()
                .add("username", name)
                .add("money", String.valueOf(money))
                .build();

        final Request request = new Request.Builder()
                .url("https://d30n971042.imdo.co/user/changeMoney")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                myHandler.sendEmptyMessage(CM_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String code = body.string();
                    if ("success".equals(code)) {
                        myHandler.sendEmptyMessage(CM_SUCCESS);
                    } else {
                        myHandler.sendEmptyMessage(CM_OTHER);
                    }
                    body.close();
                }
            }
        });

    }
//充值接口2
    private void PostHttpRequest2(int money) {
        RequestBody formBody = new FormBody.Builder()
                .add("username", name)
                .add("charge", String.valueOf(money))
                .build();

        final Request request = new Request.Builder()
                .url("https://d30n971042.imdo.co/user/charges")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

    }



}
